#include <stdio.h> 
#include <errno.h> 
#include <string.h>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h> 
#include <stdlib.h>
#include <getopt.h>
#include <ctype.h>
#include <time.h>
#include <pthread.h>
#include <libgen.h>
#include <sys/epoll.h> 
#include <sys/resource.h>




#define MAX_EVENTS         512
#define ARRAY_SIZE(x)      (sizeof(x)/sizeof(x[0]))


static inline void print_usage(char * progname);
int socket_server_init(char *listen_ip,int listen_port);
void set_socket_rlimit(void);

static inline void print_usage(char *progname)
{
      printf("%s usage: \n",progname);
      printf("-d(daemon)set programe running on back ground\n");
      printf("-p(--port):sepcify server listen port.\n");
      printf("-h(--help):printf this help information.\n");

      return ;
}



int main(int argc,char **argv)
{
    int                     rv=-1;
    int                     port=0;
    int                     ch;
    int                     opt; 
    int                     listenfd,connfd;
    int                     daemon_run=0;
    char                   *progname= NULL;
    int                     i,j;
    int                     found;
    char                    buf[1024];

    int                     epollfd;
    struct epoll_event      event; 
    struct epoll_event      event_array[MAX_EVENTS]; 
    int                     events; 

    struct option           opts[]=
    {
            {"daemon",no_argument,NULL,'b'},
	    {"port",required_argument,NULL,'p'},
            {"help",no_argument,NULL,'h'},
	    {NULL,0,NULL,0}                             
    };

    progname = basename(argv[0]);

    //解析命令参数
    while ( (ch=getopt_long(argc,argv,"bp:h",opts,NULL)) != -1)     
    {
         
	  switch (ch)
	  {
                  case 'b':
			  daemon_run=1;
			  break;


                  case 'p':
                          port=atoi(optarg);
                          break;

                  case 'h':
                          print_usage(argv[0]);
                          return 0;			  
	  }  
    }
    
    if( !port)
    {
	    print_usage(argv[0]);
	    return 0;
     
    }
 

    set_socket_rlimit();                    //设置最大打开套接字计数

    if(listenfd=socket_server_init(NULL,port)<0)      //监听listen
    {
	    printf("ERROR: %s server listen on port %d failure\n",argv[0],port);
	    return -1;
    
    }   
    printf("%s server start to listen on port %d successful\n",argv[0],port);

    if( daemon_run)                              //是否转到后台
    {
	    daemon(0,0);
    }


    if( (epollfd=epoll_create(MAX_EVENTS)) < 0 ) 
    {
	     printf("epoll_create() failure: %s\n", strerror(errno)); 
	     return -2; 
    }
	     
    event.events = EPOLLIN; 
    event.data.fd = listenfd;

    if( epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &event) < 0) 
    {

	   printf("epoll add listen socket failure: %s\n", strerror(errno));
	   return -3;
    }

    while (1)
    {
	    //程序将在此被阻塞
	    events = epoll_wait(epollfd, event_array, MAX_EVENTS, -1); 
	    if(events<0)
	    {
		    printf("epoll failure: %s\n",strerror(errno));
		    break;
	    }
	    else if(events == 0)
	    {
		    printf("epoll get timeout\n");
		    continue;
	    }


            for(i=0; i<events; i++) 
	    {
		    if ( (event_array[i].events&EPOLLERR) || (event_array[i].events&EPOLLHUP) ) 
		    {
			    printf("epoll_wait get error on fd[%d]: %s\n", event_array[i].data.fd, strerror(errno)); 
                            epoll_ctl(epollfd, EPOLL_CTL_DEL, event_array[i].data.fd, NULL); 
			    close(event_array[i].data.fd);
		    }


                    //listen socket get event表示新客户端现在开始连接
             if( event_array[i].data.fd == listenfd )
	     {
		     if( (connfd=accept(listenfd, (struct sockaddr *)NULL, NULL)) < 0) 
		     {
			     printf("accept new client failure: %s\n", strerror(errno)); 
			     continue;
		     }

		     event.data.fd = connfd;
		     event.events =  EPOLLIN;

		     if( epoll_ctl(epollfd, EPOLL_CTL_ADD, connfd, &event) < 0 )
		     {
			      printf("epoll add client socket failure: %s\n", strerror(errno)); 
			      close(event_array[i].data.fd); 
			      continue;
		     } 
		     printf("epoll add new client socket[%d] ok.\n", connfd);
	     }
	     else            //已连接客户端套接字获取数据
	     {
		     if( (rv=read(event_array[i].data.fd, buf, sizeof(buf))) <= 0) 
		     {
			     printf("socket[%d] read failure or get disconncet and will be removed.\n", event_array[i].data.fd); 
			     epoll_ctl(epollfd, EPOLL_CTL_DEL, event_array[i].data.fd, NULL);
			     close(event_array[i].data.fd); 
			     continue;
		     }
		     else
		     {
			     printf("socket[%d] read get %d bytes data\n", event_array[i].data.fd, rv);
			      

			     for(j=0; j<rv; j++)
		          	       buf[j]=toupper(buf[j]);


			     if( write(event_array[i].data.fd, buf, rv) < 0 )
			     {
				     printf("socket[%d] write failure: %s\n", event_array[i].data.fd, strerror(errno)); 
				     epoll_ctl(epollfd, EPOLL_CTL_DEL, event_array[i].data.fd, NULL);
				     close(event_array[i].data.fd); 
			     }
		     }

	     }
	    }
    }

close(listenfd);
return 0;
}



int socket_server_init(char *listen_ip, int listen_port) 
{
         struct sockaddr_in      serv_addr;
	 int                     rv = 0;
	 int                     on = 1;
	 int                     listenfd;

if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
	printf("Use socket() to create a TCP socket failure: %s\n", strerror(errno)); 
	return -1;
}
    
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(listen_port);
    //inet_aton( "", &serv_addr.sin_addr );
  
    if( !listen_ip)
    {
	    serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
	
    }
    else 
    {
	    if (inet_pton(AF_INET, listen_ip, &serv_addr.sin_addr) <= 0)  
	    {
		     printf("inet_pton() set listen IP address failure.\n"); 
		     rv = -2;
		     goto cleanup;
	    }
    }

    if(bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0);  
    {
           printf("use bind failure: %s\n", strerror(errno)); 
	   rv = -3;
	   goto cleanup;
           
    } 
    
    if(listen(listenfd,13)<0);
    {
           printf("listen on portr[%d] failure\n",strerror(errno));
	   rv = -4;
	   goto cleanup;
    }

cleanup:
    if(rv<0)
	close(listenfd);
    else
        rv = listenfd;
    
    return rv;
 }



//将“打开文件描述计数”设置为“最大”
void set_socket_rlimit(void) 
{
	struct rlimit limit = {0};

	getrlimit(RLIMIT_NOFILE, &limit ); 
	limit.rlim_cur  = limit.rlim_max; 
	setrlimit(RLIMIT_NOFILE, &limit );
	 
	printf("set socket open fd max count to %d\n", limit.rlim_max);
}
	    

